package io.adrainty.bolee.framework.gateway.filter;

import io.adrainty.bolee.framework.commons.basic.ResponseCode;
import io.adrainty.bolee.framework.commons.properties.SecurityConfigProperties;
import io.adrainty.bolee.framework.commons.constants.GlobalOauth2Constants;
import io.adrainty.bolee.framework.gateway.utils.RequestHelper;
import io.adrainty.bolee.framework.gateway.utils.ResponseHelper;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/7/28 上午1:06
 */

@Component
public class UserTokenGlobalFilter extends BaseFilter {

    @Resource
    private SecurityConfigProperties properties;

    @Override
    protected Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String tokenValue = RequestHelper.getFirstHeader(request, GlobalOauth2Constants.USER_TOKEN);
        if (StringUtils.isBlank(tokenValue)) {
            return ResponseHelper.writeFailed(exchange.getResponse(), ResponseCode.USER_NOT_LOGIN, HttpStatus.UNAUTHORIZED);
        }

        request = request.mutate().header(GlobalOauth2Constants.USER_TOKEN, tokenValue).build();
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    protected boolean isFilter(String path, boolean isUploadRequest, ServerHttpRequest request) {
        HttpMethod method = request.getMethod();
        if (HttpMethod.OPTIONS.equals(method)) return false;
        return nonePathMatch(properties.getIgnoreUrl(), path);
    }

}
